<template>
  <div class="container">
    <div class="content">
      <uv-sticky bgColor="#fff">
        <view class="search-box">
          <uv-search @change="changeFn" placeholder="请输入任务名" :show-action="false" :border="false" bgColor="#FFFFFF" borderColor="#d8d8d8"
                     v-model="queryParams.taskName" shape="square" :clearabled="true" @clear="clear"></uv-search>
          <uv-subsection :list="list1" :current="current" @change="clickFn"
                         mode="button"></uv-subsection>
          <uv-drop-down
              ref="dropDown"
              sign="dropDown_1"
              :extra-icon="{name:'arrow-down-fill',color:'#666',size:'26rpx'}"
              :extra-active-icon="{name:'arrow-up-fill',color:'#3c9cff',size:'26rpx'}"
              :defaultValue="defaultValue"
              :custom-style="{padding: '0 100rpx'}"
              @click="selectMenu"
          >
            <uv-drop-down-item
                name="area"
                type="2"
                :label="dropItem('area').label"
                :value="dropItem('area').value">
            </uv-drop-down-item>
            <uv-drop-down-item
                name="type"
                type="2"
                :label="dropItem('type').label"
                :value="dropItem('type').value">
            </uv-drop-down-item>
          </uv-drop-down>
          <uv-drop-down-popup
              sign="dropDown_1"
              :click-overlay-on-close="true"
              :currentDropItem="currentDropItem"
              @clickItem="clickItem"
          ></uv-drop-down-popup>
        </view>
      </uv-sticky>

      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
        <div class="list-item" v-for="(item, index) in dataList" :key="index" @tap="GoUpload(item,0)">
          <div class="flex-box">
            <div class="wid">
              <div class="flex">
                <uv-text :lines="2" class="first" :text="item.title"></uv-text>
              </div>
            </div>

            <div class="flex">
              <uv-tags v-if="item.status===0" :text="'待提交'" type="error" size="mini" plain></uv-tags>
              <uv-tags v-else-if="item.status===1" :text="'待检查'" type="success" size="mini" plain></uv-tags>
              <uv-tags v-else-if="item.status===2" :text="'已完成'" type="primary" size="mini" plain></uv-tags>
              <uv-tags v-else :text="'未完成'" type="warning" size="mini" plain></uv-tags>
            </div>
          </div>

          <div class="flex">
            <div :class="item.userName ?'text-gray':'text-red'">执行人：{{ item.userName ? item.userName : '未指定' }}
            </div>
            <uv-rate size="20" v-model="item.score" :allowHalf="true" readonly
                     v-if="item.status === 2 && item.score >= 0"></uv-rate>

            <uv-text type="info" :text="item.score" v-if="item.status === 2 && item.score >= 0"></uv-text>

            <div class="flex">
              <!-- 任务类型 -->
              <uv-text v-for="dict in typeData  "
                       :key="dict.dictKey"
                       v-if="item.timeType == dict.dictKey"
                       :text="dict.dictValue"
                       type="info"
                       bold
              ></uv-text>
            </div>
          </div>
          <div class="flex">
            <div class="text-gray" style="flex:1;">检查人：{{ item.inspectorName }}</div>
            <uv-text v-if="item.rejectReason" lines="1" :text="`驳回：${item.rejectReason}`" type="error"
                     margin="20"></uv-text>
          </div>
          <div class="flex">
            <div class="text-gray">下发人：{{ item.createUserName }}</div>
            <div>
              <uv-text type="warning" text="未评分" v-if="item.status === 2 && item.score < 0"></uv-text>
            </div>
          </div>
          <div class="flex">
            <div class="text-gray">执行截止日期：
              <span v-if="item.status ===0 || item.status === 1"
                    :class="item.deadlineStatus ?'text-red':'text-gray'">{{ item.deadline }}</span>
              <span v-else class="text-gray">{{ item.deadline }}</span>
            </div>
          </div>
          <div class="flex">
            <div class="text-gray">检查截止日期：
              <span v-if="item.status ===0 || item.status === 1"
                    :class="item.inspectDeadlineStatus ?'text-red':'text-gray'">{{ item.inspectDeadline }}</span>
              <span v-else class="text-gray">{{ item.inspectDeadline }}</span>
            </div>
            <div class="flex">
              <uv-button type="primary" text="去检查" size="mini"
                         v-if="(userId === item.inspectorId) && item.status === 1 && !item.inspectDeadlineStatus"></uv-button>
              <div style="width: 10px;"></div>
              <uv-button type="primary" text="去提交" size="mini"
                         v-if="(userId === item.userId) && item.status === 0 && !item.deadlineStatus"></uv-button>
            </div>
          </div>
        </div>
      </mescroll-body>
    </div>
  </div>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import TaskAPI from '@/api/task'
import DictAPI from "@/api/dict";
import AreaAPI from "@/api/area";

export default {
  onPageScroll() {
    // 滚动后及时更新位置
    this.$refs.dropDown.init();
  },
  computed: {
    dropItem(name) {
      return (name) => {
        const result = {};
        const find = this.result.find(item => item.name === name);
        if (find) {
          result.label = find.label;
          result.value = find.value;
        } else {
          result.label = this[name].label;
          result.value = this[name].value;
        }
        return result;
      }
    },
    // 获取当前下拉筛选项
    currentDropItem() {
      return this[this.activeName];
    }
  },
  mixins: [MescrollMixin], // 使用mixin
  comments: {},
  data() {
    return {
      // 表示value等于这些值，就属于默认值
      defaultValue: ['all'],
      // 筛选结果
      result: [],
      activeName: 'area',
      area: {
        label: '区域',
        value: 'all',
        activeIndex: 0,
        color: '#333',
        activeColor: '#2878ff',
        child: []
      },
      type: {
        label: '任务类型',
        value: 'all',
        activeIndex: 0,
        color: '#333',
        activeColor: '#2878ff',
        child: []
      },
      current: 0,
      list1: [{
        name: '待提交',
        value: 0,
      }, {
        name: '待检查',
        value: 1,
      }, {
        name: '已完成',
        value: 2,
      },
        {
          name: '未完成',
          value: 3,
        }
      ],
      queryParams: {
        current: 1,
        size: 10,
        taskProgressStatus: 0, // 0 待处理 1 待检查 2 已完成 3 未完成
      },
      dataList: [],
      total: 0,
      show: false,
      form: {},
      authority: 'employee', // admin、employee、store_manager、dept_manager
      userId: '',
      typeData: []
    }
  },
  onShow(e) {
    //(内部会自动page.num=1,再主动触发up.callback)
    this.mescroll.resetUpScroll();

    this.authority = uni.getStorageSync('authInfo')?.authority
    this.userId = uni.getStorageSync('authInfo')?.userId

    this.init()
  },
  methods: {
    init() {
      AreaAPI.tree(1).then(res => {
        this.area.child = res.data.map(item => {
          return {
            label: item.title,
            value: item.id
          }
        })
        this.area.child.unshift({
          label: '全部',
          value: 'all'
        })
      })

      DictAPI.dictByCodeList({code: 'task_time_type'}).then(res => {
        this.typeData = res.data
        this.type.child = res.data.map(item => {
          return {
            label: item.dictValue,
            value: item.dictKey
          }
        })
        this.type.child.unshift({
          label: '全部',
          value: 'all'
        })
      })
    },
    GoUpload(item, edit) {
      if (edit === 1) {
        uni.navigateTo({
          url: `/pages/usertask/taskdetail?id=${item.id}&edit=1`
        })
      } else {
        uni.navigateTo({
          url: `/pages/usertask/taskdetail?id=${item.id}&edit=0`
        })
      }
    },
    /*上拉加载的回调*/
    upCallback(page) {
      let me = this
      me.queryParams.current = page.num; // 页码, 默认从1开始
      TaskAPI.taskRecordList(me.queryParams).then(res => {
        let curPageData = res.data.records
        // 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
        let curPageLen = curPageData.length;
        // 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
        let totalPage = res.data.totalPage
        me.total = res.data.total
        //设置列表数据
        if (page.num === 1) this.dataList = []; //如果是第一页需手动置空列表

        // 任务标题
        curPageData.forEach(item => {
          let title = ''
          if (item.areaName) {
            title = item.areaName + '-'
          }
          if (item.taskName) {
            title += item.taskName
          }

          item.title = title

          // 任务是否到截止日期
          if (item.deadline) {
            let now = new Date().getTime()
            let deadline = new Date(item.deadline).getTime()
            if (now > deadline) {
              item.deadlineStatus = true
            }
          }

          // 任务是否到截止日期
          if (item.inspectDeadline) {
            let now = new Date().getTime()
            let inspectDeadline = new Date(item.inspectDeadline).getTime()
            if (now > inspectDeadline) {
              item.inspectDeadlineStatus = true
            }
          }
        })

        this.dataList = this.dataList.concat(curPageData); //追加新数据

        // 请求成功,隐藏加载状态
        //方法一(推荐): 后台接口有返回列表的总页数 totalPage
        this.mescroll.endByPage(curPageLen, totalPage);
      })
    },

    // 状态切换刷新列表
    clickFn(e) {
      console.log(e)
      this.current = e;

      let me = this;
      me.queryParams.current = 1
      me.queryParams.taskProgressStatus = e
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },

    changeFn() {
      let me = this;
      me.queryParams.current = 1
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    clear() {
      this.queryParams = {
        current: 1,
        size: 10
      }
      this.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },

    /**
     * 点击每个筛选项回调
     * @param {Object} e { name, active, type } = e
     */
    selectMenu(e) {
      const {name, active, type} = e;
      this.activeName = name;
      // type 等于1 的需要特殊处理：type不等于1可以忽略
      const find = this.result.find(item => item.name === this.activeName);
      if (find) {
        this[this.activeName].activeIndex = this[this.activeName].child.findIndex(item => item.label === find.label && item.value === find.value);
      } else {
        this[this.activeName].activeIndex = 0;
      }
    },
    /**
     * 点击菜单回调处理
     * @param {Object} e 选中项 { label,value } = e
     */
    clickItem(e) {
      // 下面有重新赋值，所以用let
      let {label, value} = e;
      const findIndex = this.result.findIndex(item => item.name === this.activeName);
      if (this.defaultValue.indexOf(value) > -1 && this[this.activeName].label) {
        label = this[this.activeName].label;
      }
      // 已经存在筛选项
      if (findIndex > -1) {
        this.$set(this.result, findIndex, {
          name: this.activeName,
          label,
          value
        })
      } else {
        this.result.push({
          name: this.activeName,
          label,
          value
        });
      }
      this.result = this.result.filter(item => this.defaultValue.indexOf(item.value) === -1);

      this.queryParams.areaId = this.result.find(item => item.name === 'area')?.value || ''
      this.queryParams.timeType = this.result.find(item => item.name === 'type')?.value || ''
      this.changeFn()
    },
  }
}
</script>

<style scoped>
.content {
  margin: auto 0.3rem;
}

.list-item {
  width: 90%;
  margin: 0.3rem auto;
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.flex-box {
  display: flex;
  justify-content: space-between;
}

.wid {
  width: 80%;
}

.flex {
  display: flex;
  justify-content: space-between;
  line-height: 1.4rem;
}

.first {
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.text-gray {
  font-size: 14px;
  color: gray;
  margin: 0.2rem 0;
}

.text-red {
  font-size: 14px;
  color: red;
  margin: 0.2rem 0;
}

.right {
  text-align: right;
}
</style>